//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import type { EvaluateInfo, MyEvaluateResult, MyEvaluateItem } from "@/api/org_evaluate";
import { EVALUATE_STATE_EVALUATE, get_my_evaluate, update_my_evaluate } from "@/api/org_evaluate";
import { Card, Descriptions, List, message, Modal, Rate, Space, Tabs } from "antd";
import { observer } from 'mobx-react';
import { useStores } from "@/hooks";
import UserPhoto from "@/components/Portrait/UserPhoto";
import { request } from "@/utils/request";

export interface ViewEvalModalProps {
    evalInfo: EvaluateInfo;
    onClose: () => void;
    onChange: () => void;
}

const ViewEvalModal = (props: ViewEvalModalProps) => {
    const userStore = useStores("userStore");
    const orgStore = useStores("orgStore");

    const [activeKey, setActiveKey] = useState<"summary" | "my">("summary");
    const [hasFooter, setHasFooter] = useState(false);
    const [voteItemList, setVoteItemList] = useState<MyEvaluateResult[]>([]);

    const loadVoteItemList = async () => {
        let hasVoted = false;
        for (const memberItem of props.evalInfo.member_list) {
            if (memberItem.member_user_id == userStore.userInfo.userId) {
                hasVoted = memberItem.has_evaluate;
            }
        }
        if (hasVoted) {
            const res = await request(get_my_evaluate({
                session_id: userStore.sessionId,
                org_id: orgStore.curOrgId,
                evaluate_id: props.evalInfo.evaluate_id,
            }));
            setVoteItemList(res.result_list);
        } else {
            const tmpList: MyEvaluateResult[] = [];
            for (const memberItem of props.evalInfo.member_list) {
                const voteItem: MyEvaluateResult = {
                    member_user_id: memberItem.member_user_id,
                    member_display_name: memberItem.member_display_name,
                    member_logo_uri: memberItem.member_logo_uri,
                    score_list: memberItem.score_list.map(item => ({
                        target_id: item.target_id,
                        target_name: item.target_name,
                        score: 0,
                    })),
                };
                tmpList.push(voteItem);
            }
            setVoteItemList(tmpList);
        }
    };

    const doVote = async () => {
        const tmpList: MyEvaluateItem[] = [];
        for (const voteItem of voteItemList) {
            tmpList.push({
                member_user_id: voteItem.member_user_id,
                score_list: voteItem.score_list.map(scoreItem => ({
                    target_id: scoreItem.target_id,
                    score: scoreItem.score,
                }))
            });
        }
        await request(update_my_evaluate({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            evaluate_id: props.evalInfo.evaluate_id,
            item_list: tmpList,
        }));
        message.info("投票成功");
        props.onChange();
    };

    useEffect(() => {
        if (activeKey == "summary") {
            setHasFooter(false);
        } else if (activeKey == "my") {
            if (props.evalInfo.member_list.map(item => item.member_user_id).includes(userStore.userInfo.userId)) {
                if (props.evalInfo.evaluate_state == EVALUATE_STATE_EVALUATE) {
                    setHasFooter(true);
                } else {
                    setHasFooter(false);
                }
            } else {
                setHasFooter(false);
            }
            loadVoteItemList();
        }
    }, [activeKey]);

    return (
        <Modal open footer={hasFooter ? undefined : null} mask={false}
            okText="更新"
            bodyStyle={{ padding: "6px 10px" }} width={900}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onClose();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                doVote();
            }}>
            <Tabs activeKey={activeKey} onChange={value => setActiveKey(value as "summary" | "my")} type="card">
                <Tabs.TabPane key="summary" tab="评估概览">
                    {activeKey == "summary" && (
                        <List rowKey="member_user_id" dataSource={props.evalInfo.member_list} grid={{ gutter: 16 }}
                            style={{ maxHeight: "calc(100vh - 300px)", overflowY: "scroll", width: "880px", overflowX: "hidden" }}
                            pagination={false} renderItem={item => (
                                <List.Item>
                                    <Card title={
                                        <Space>
                                            <UserPhoto logoUri={item.member_logo_uri} style={{ width: "16px", height: "16px", borderRadius: "10px" }} />
                                            {item.member_display_name}
                                        </Space>
                                    } style={{ width: "280px" }} headStyle={{ backgroundColor: "#eee" }}>
                                        <Descriptions bordered={false} column={1} labelStyle={{ width: "100px", textOverflow: "ellipsis", overflow: "hidden", whiteSpace: "nowrap" }}>
                                            {item.score_list.map(scoreItem => (
                                                <Descriptions.Item label={scoreItem.target_name}>
                                                    <div style={{ display: "flex", width: "140px" }}>
                                                        <div style={{ flex: 1 }}>总分:&nbsp;{scoreItem.score}</div>
                                                        <div style={{ flex: 1 }}>平均分:&nbsp;{(scoreItem.score / props.evalInfo.member_list.length).toFixed(2)}</div>
                                                    </div>
                                                </Descriptions.Item>
                                            ))}
                                        </Descriptions>
                                    </Card>
                                </List.Item>
                            )} />
                    )}

                </Tabs.TabPane>
                {props.evalInfo.member_list.map(item => item.member_user_id).includes(userStore.userInfo.userId) && (
                    <Tabs.TabPane key="my" tab="我的投票">
                        {activeKey == "my" && (
                            <List rowKey="member_user_id" dataSource={voteItemList} pagination={false}
                                style={{ maxHeight: "calc(100vh - 300px)", overflowY: "scroll", width: "880px", overflowX: "hidden" }}
                                renderItem={item => (
                                    <Card title={
                                        <Space>
                                            <UserPhoto logoUri={item.member_logo_uri} style={{ width: "16px", height: "16px", borderRadius: "10px" }} />
                                            {item.member_display_name}
                                        </Space>
                                    } style={{ width: "100%" }} bordered={false} headStyle={{ backgroundColor: "#eee" }}>
                                        <Descriptions column={1} bordered={false} labelStyle={{ width: "100px", textOverflow: "ellipsis", overflow: "hidden", whiteSpace: "nowrap" }}>
                                            {item.score_list.map(scoreItem => (
                                                <Descriptions.Item key={scoreItem.target_id} label={scoreItem.target_name}>
                                                    <Rate value={scoreItem.score} count={10} onChange={value => {
                                                        const tmpList = voteItemList.slice();
                                                        const index1 = tmpList.findIndex(subItem => subItem.member_user_id == item.member_user_id);
                                                        const index2 = tmpList[index1].score_list.findIndex(subItem => subItem.target_id == scoreItem.target_id);
                                                        tmpList[index1].score_list[index2].score = value;
                                                        setVoteItemList(tmpList);
                                                    }} disabled={props.evalInfo.evaluate_state != EVALUATE_STATE_EVALUATE}/>
                                                </Descriptions.Item>
                                            ))}
                                        </Descriptions>
                                    </Card>
                                )} />
                        )}
                    </Tabs.TabPane>
                )}
            </Tabs>
        </Modal>
    );
};

export default observer(ViewEvalModal);